﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RBAC.Api.Infaction
{
    public class BaseRepositry<T> : IBaseRepositry<T> where T : class
    {
        private readonly MyDbContext Db;

        public BaseRepositry(MyDbContext myDbContext)
        {
            Db = myDbContext;
            Db = Db;
        }

        public MyDbContext Context
        {
            get { return Db; }
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public async Task<int> Add(T item)
        {
            await Db.Set<T>().AddAsync(item);
            return await Db.SaveChangesAsync();
        }
        /// <summary>
        /// 批量添加
        /// </summary>
        /// <param name="items"></param>
        /// <returns></returns>
        public async Task<int> AddAsync(IEnumerable<T> items)
        {
            await Db.Set<T>().AddRangeAsync(items);
            return await Db.SaveChangesAsync();
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public async Task<int> Delete(T item)
        {
            Db.Set<T>().Remove(item);
            return await Db.SaveChangesAsync();
        }
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="items"></param>
        /// <returns></returns>
        public async Task<int> DeleteAsync(IEnumerable<T> items)
        {
            Db.Set<T>().RemoveRange(items);
            return await Db.SaveChangesAsync();
        }

        public T Find(int id)
        {
            throw new NotImplementedException();
        }

        public IQueryable<T> GetAll()
        {
            return Db.Set<T>().AsQueryable();
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public async Task<int> Update(T item)
        {
            Db.Set<T>().Update(item);
            return await Db.SaveChangesAsync();
        }
        /// <summary>
        /// 批量修改
        /// </summary>
        /// <param name="items"></param>
        /// <returns></returns>
        public async Task<int> UpdateAsync(IEnumerable<T> items)
        {
            Db.Set<T>().UpdateRange(items);
            return await Db.SaveChangesAsync();
        }
    }
}
